import babel from "@rollup/plugin-babel";
import nodeResolve from "@rollup/plugin-node-resolve";
import fs, { outputFileSync } from "fs-extra";
import postcss from "rollup-plugin-postcss";
import commonjs from "@rollup/plugin-commonjs";
import analyze from "rollup-plugin-analyzer";

// ! 不要妄想使用 importsmap 导入 @codingame/monaco-editor 或者是其他库，这些库没有后缀名，属于 nodejs 代码文件
const clears = fs.readdirSync("./dist/").filter((i) => {
    return !["editor", "features", "analyze", "wrapper", "api"].includes(i);
});
clears.forEach((i) => {
    try {
        fs.removeSync("./dist/" + i);
    } catch (e) {
        fs.emptyDirSync("./dist/" + i);
    }
});

// rollup.config.js
export default {
    external: [
        "@codingame/monaco-editor",
        "solid-js",
        "solid-js/web",
        "prettier",
        "vscode",
    ],
    input: "./src/index.ts",
    output: {
        dir: "./dist/",
        format: "es",
        paths: {
            prettier:
                "https://cdn.jsdelivr.net/npm/prettier/esm/standalone.mjs",
            vscode: "./api/api.js",
        },
    },
    plugins: [
        {
            resolveId(thisFile, importer) {
                if (thisFile === "lib/features.js") {
                    return { external: true, id: "./features/features.js" };
                }
                if (thisFile === "@codingame/monaco-editor-wrapper") {
                    return { external: true, id: "./wrapper/wrapper.js" };
                }
                if (thisFile.startsWith("@codingame/monaco-vscode-api/dist")) {
                    const id = thisFile.replace(
                        "@codingame/monaco-vscode-api/dist",
                        "./api"
                    );
                    return { external: true, id: id + ".js" };
                }
                if (["monaco-editor"].some((i) => thisFile.startsWith(i))) {
                    return {
                        external: true,
                        id: thisFile.replace(
                            "monaco-editor/esm/vs",
                            "../editor"
                        ),
                    };
                }
                if (thisFile.startsWith("https://")) {
                    return false;
                }

                if (!/^[[\w:]|\.|\/]/.test(thisFile)) console.log(thisFile);
            },
        },

        nodeResolve({
            browser: true,
            extensions: [".ts", ".tsx", ".js"],
        }),
        commonjs(),
        // 解决 svg 模块问题
        {
            name: "svg",
            async load(id) {
                if (id.endsWith(".svg")) {
                    const code = await fs.promises.readFile(id, "utf8");
                    return {
                        code: `export default ()=>(new DOMParser().parseFromString(${JSON.stringify(
                            code
                        )}, 'image/svg+xml')).firstChild`,
                    };
                }
            },
        },
        postcss({
            inject: true,
            minimize: {},
            modules: {},
            sourceMap: false,
            extensions: [".css", ".less"],
        }),
        babel({
            babelHelpers: "bundled",
            extensions: [".ts", ".tsx", ".js", ".svg"],
            exclude: ["**/@codingame/**/*"],
        }),
        analyze({
            summaryOnly: true,
            writeTo: (str) =>
                outputFileSync("dist/analyze/index.analyze.txt", str),
        }),
    ],
};
